<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class De_indicator_model extends MY_Model {

    function __construct() {
        parent::__construct("indicator", "id", Array(
                ), "data_ps");
    }

    protected function read($where = Array(), $fetchForeign = false, $depth = 1, $page = -1, $limit = 10) {
        $results = parent::read($where, $fetchForeign, $depth, $page, $limit);

        foreach ($results as $result) {
            $query = $this->db->query("SELECT indicator.id FROM  `indicator` WHERE  `parent_id` = " . $result->id . " LIMIT 1");
            $result->has_child = count($query->result()) > 0;
        }

        return $results;
    }

    public function create($name, $hasValue, $metric, $desc, $parentId) {
        return parent::create(Array(
                    "name" => $name,
                    "has_value" => $hasValue,
                    "metric" => $metric,
                    "desc" => $desc,
                    "parent_id" => $parentId
        ));
    }

    public function deleteById($id) {
        if ($id > 0) {
            // do deletion
            //--> delete childs
            foreach ($this->findAll(Array("parent_id" => $id)) as $child) {
                $this->deleteById($child->id);
            }
            //--> delete datas
            //.....
            return parent::deleteById($id);
        } else {
            return 0;
        }
    }

    public function getChilds($id) {
        $childs = $this->de_indicator_model->findAll(Array("parent_id" => $id));
        return $childs;
    }

    public function getTreeJSON($rootId) {
        $obj = $this->de_indicator_model->findById($rootId);
        $jsonObj = new stdClass();
        if ($obj != NULL) {
            $jsonObj->name = "[" . $obj->id . "] " . $obj->name;
            if ($obj->has_child) {
                $jsonObj->children = Array();
                foreach ($this->getChilds($obj->id) as $child) {
                    array_push($jsonObj->children, $this->getTreeJSON($child->id));
                }
            } else {
                $jsonObj->size = 5000;
            }
        }
        return $jsonObj;
    }

}